﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace SaturniLibrary.Web
{
    public static class ControllerExtensions
    {
        /// <summary>
        /// 获取View输出
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="viewName">View路径</param>
        /// <returns></returns>
        public static string RenderViewToString(this Controller controller, string viewName)
        {
            IView view = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null).View;
            using (StringWriter sw = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, sw);
                viewContext.View.Render(viewContext, sw);
                return sw.ToString();
            }
        }

        /// <summary>
        /// 获取View输出,指定masterName
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="viewName">View路径</param>
        /// <param name="masterName">Layout路径</param>
        /// <returns></returns>
        public static string RenderViewToString(this Controller controller, string viewName, string masterName)
        {
            IView view = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName).View;
            using (StringWriter sw = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, sw);
                viewContext.View.Render(viewContext, sw);
                return sw.ToString();
            }
        }

        /// <summary>
        /// 获取Partial输出
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="partialViewName">partialView路径</param>
        /// <returns></returns>
        public static string RenderPartialViewToString(this Controller controller, string partialViewName)
        {
            IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
            using (StringWriter sw = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, sw);
                viewContext.View.Render(viewContext, sw);
                return sw.ToString();
            }
        }
    }
}
